/* ****************************
 *@description: 封装axios
 *@author:rennan
 *@date: 2023-03-29 20:35:12
 *@version: V1.0.0
*****************************/
import axios from 'axios'
import utils from '../utils/utils'
import { resetRouter } from '@/router/index.js'
import qs from 'qs'

axios.defaults.withCredentials = true;
const instance = axios.create({
  // baseURL: 'http://47.100.65.29:8002/',
  baseURL: process.env.BASE_API,
  //withCredentials:true, //是否允许跨域
  timeout: 5000,
})

// 请求拦截
instance.interceptors.request.use(config => {
  let tk = utils.getToken()
  if (tk) {
    config.headers['Authorization'] = tk
  }
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截
// instance.interceptors.response.use(response => {
//   const res = response.data
//   if (res.status !== 200) {
//     if (res.status === 500) {
//       utils.showWarning(res.message)
//     }
//     if (res.status === 401) {
//       logout()
//     }
//     // 返回失败对象
//     return Promise.reject(new Error(res.message || 'Error'))
//   } else {
//     return res
//   }
// }, err => {
//   utils.showWarning(err.message)
//   return Promise.reject(err)
// })

// 封装get请求
export function get(url, params) {
  return instance.get(url, {
    params,
    timeout: 10000,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装delete请求
export function del(url, params) {
  return instance.delete(url, {
    params,
    timeout: 10000,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
}

// 封装post请求
export function post(url, data) {
  return instance.post(url, qs.stringify(data), {
    timeout: 10000,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  })
}

// 退出
async function logout() {
  utils.removeToken()
  resetRouter()
  router.replace('/login')
}
export default instance